package de.fhhof.robot.control.app;

import java.util.Observable;

import de.fhhof.robot.control.ApplicationStorage;
import de.fhhof.robot.control.IMessage;
import de.fhhof.robot.control.cmd.SAPCommandFactory;
import de.fhhof.robot.control.cmd.concreate.AssemblyState;
import de.fhhof.robot.control.cmd.concreate.CmdAbortAssemblyProcess;
import de.fhhof.robot.control.common.CommonConstants;
import de.fhhof.robot.control.impl.ControlToJsap;
import de.fhhof.robot.control.net.Connection;
import de.fhhof.robot.control.net.IConnection;

public class CommandReceiver extends Observable implements Runnable {

	private ApplicationStorage<AssemblyState>  storage = new ApplicationStorage<AssemblyState>();
	
	@Override
	public void run() {
		
		while(true){
			/** If there is any pending assembly command then start it again. */
			IMessage crashedMessage = recoverCrashedCommand();
			if(crashedMessage != null){
				setChanged();
				notifyObservers(crashedMessage);
			}
			/** Read request from JSAP */
			IMessage message = getJSAPMessage();
			setChanged();
			notifyObservers(message);
		}
		
	}
	private IMessage getJSAPMessage(){
		IConnection jsapClient = ControlToJsap.getJsapConnection();
		IMessage message = jsapClient.receive();
		return message;
	}
	
	private IMessage recoverCrashedCommand(){
		
		if(SAPCommandFactory.getCurrentAssemblyCommand() != null){
			return null;
		}
		IMessage msg = null;
		try{
			AssemblyState state = storage.restore(CommonConstants.STORAGE_FILE_NAME);
			if(state == null){
				return null;
			}
			msg = state.getAssemblyMessage();
			if(msg != null){
				System.out.println("System is recovering from serious error.");
			}
		}
		catch(Exception ex){
			System.out.println("Error occured during loading recovery file: "+ex.getMessage());
		}
		return msg;
	}
	

}
